package chexuan.game.service.config;

import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;

import org.dom4j.Document;
import org.dom4j.Element;

import chexuan.game.interfaces.common.InterfaceConfigrurationCommit;
import chexuan.game.interfaces.common.InterfaceServiceConfiguration;

public class ConfigurationCollector implements InterfaceConfigrurationCommit {

	private final ArrayList<InterfaceServiceConfiguration> list;
	private Document document = null;

	public ConfigurationCollector() {
		list = new ArrayList<InterfaceServiceConfiguration>();
	}

	public void setDocument(Document document) {
		this.document = document;
	}

	public Document getDocument() {
		return this.document;
	}

	public void readConfigruation(Document document) {
		Element root = document.getRootElement();

		for (InterfaceServiceConfiguration serviceConfiguration : list) {
			String serviceConfigurationRoot = serviceConfiguration
					.getServiceConfigurationRootElement();
			Iterator<Element> elements = root
					.elementIterator(serviceConfigurationRoot);
			serviceConfiguration.readConfigration(elements, root);
		}
	}

	public void writeConfigration(Document document) {
		Element root = document.getRootElement();

		for (InterfaceServiceConfiguration serviceConfiguration : list) {
			String serviceConfigrationRoot = serviceConfiguration
					.getServiceConfigurationRootElement();
			Iterator<Element> elements = root
					.elementIterator(serviceConfigrationRoot);
			serviceConfiguration.writeConfigration(elements, root);
		}
	}

	@Override
	public void commit(InterfaceServiceConfiguration configruation) {
		commit(configruation, document);
	}

	private void commit(InterfaceServiceConfiguration configuration,
			Document document) {
		Element root = document.getRootElement();
		String serviceConfigrationRoot = configuration
				.getServiceConfigurationRootElement();
		Iterator<Element> elements = root
				.elementIterator(serviceConfigrationRoot);
		configuration.writeConfigration(elements, root);
	}

	public void commit(FileWriter out) throws IOException {
		document.write(out);
	}

	public void registerServiceConfigration(
			InterfaceServiceConfiguration serviceConfiguration) {
		list.add(serviceConfiguration);
	}
}
